import { useEffect, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import { Engine, Scene, Vector3, HemisphericLight, ArcRotateCamera, MeshBuilder, StandardMaterial, Color3, Texture } from "@babylonjs/core";
import useCartStore from "../../stores/cartStore";

const Customization = () => {
  const { id } = useParams();
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const sceneRef = useRef<Scene | null>(null);
  const boxRef = useRef<any>(null);
  const materialRef = useRef<StandardMaterial | null>(null);
  const { addItem } = useCartStore();
  
  // Mock product data
  const product = {
    id: id,
    name: "现代简约沙发",
    basePrice: 2999,
    description: "这款现代简约沙发可定制颜色、材质和尺寸"
  };
  
  // Customization options
  const [customization, setCustomization] = useState({
    color: "#8B5CF6",
    material: "布料",
    size: "中号"
  });
  
  // Price adjustments based on customization
  const priceAdjustments = {
    material: { "布料": 0, "皮革": 500, "绒布": 300, "亚麻": 200 },
    size: { "小号": -300, "中号": 0, "大号": 500 }
  };
  
  const totalPrice = product.basePrice + 
    (priceAdjustments.material as any)[customization.material] + 
    (priceAdjustments.size as any)[customization.size];

  useEffect(() => {
    if (!canvasRef.current) return;

    const engine = new Engine(canvasRef.current, true);
    const scene = new Scene(engine);
    sceneRef.current = scene;
    
    // Create camera
    const camera = new ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2.5, 10, new Vector3(0, 0, 0), scene);
    camera.attachControl(canvasRef.current, true);
    
    // Create light
    const light = new HemisphericLight("light", new Vector3(0, 1, 0), scene);
    light.intensity = 0.7;
    
    // Create a simple box as placeholder for furniture model
    const box = MeshBuilder.CreateBox("box", { width: 2, height: 1, depth: 0.5 }, scene);
    boxRef.current = box;
    
    // Create material
    const material = new StandardMaterial("material", scene);
    material.diffuseColor = Color3.FromHexString(customization.color);
    box.material = material;
    materialRef.current = material;
    
    // Render loop
    engine.runRenderLoop(() => {
      scene.render();
    });
    
    // Handle window resize
    const resize = () => {
      engine.resize();
    };
    window.addEventListener("resize", resize);
    
    // Cleanup
    return () => {
      window.removeEventListener("resize", resize);
      scene.dispose();
      engine.dispose();
    };
  }, []);
  
  // Update 3D model when customization changes
  useEffect(() => {
    if (materialRef.current) {
      materialRef.current.diffuseColor = Color3.FromHexString(customization.color);
    }
    
    // In a real app, you would also update texture based on material selection
    // and scale based on size selection
    
    // For size changes, we would update the box dimensions
    if (boxRef.current) {
      let scale = 1;
      if (customization.size === "小号") scale = 0.8;
      if (customization.size === "大号") scale = 1.2;
      
      // In a real implementation, you would properly scale the mesh
      // boxRef.current.scaling = new Vector3(scale, scale, scale);
    }
  }, [customization]);
  
  const handleColorChange = (color: string) => {
    setCustomization({ ...customization, color });
  };
  
  const handleMaterialChange = (material: string) => {
    setCustomization({ ...customization, material });
  };
  
  const handleSizeChange = (size: string) => {
    setCustomization({ ...customization, size });
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6">定制 {product.name}</h1>
      
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* 3D Viewer */}
        <div className="lg:col-span-2 bg-white rounded-lg shadow-md p-4">
          <div className="relative h-96 w-full">
            <canvas 
              ref={canvasRef} 
              className="w-full h-full"
            />
          </div>
          <div className="mt-4 text-center text-gray-600">
            <p>拖拽鼠标旋转视角，滚动鼠标缩放</p>
          </div>
        </div>
        
        {/* Customization Options */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-2xl font-semibold mb-6">定制选项</h2>
          
          {/* Color Selection */}
          <div className="mb-6">
            <h3 className="text-lg font-medium mb-3">颜色</h3>
            <div className="flex flex-wrap gap-2">
              {["#8B5CF6", "#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#6B7280"].map((color) => (
                <button
                  key={color}
                  className={`w-10 h-10 rounded-full border-2 shadow ${
                    customization.color === color
                      ? "border-blue-500"
                      : "border-white"
                  }`}
                  style={{ backgroundColor: color }}
                  onClick={() => handleColorChange(color)}
                />
              ))}
            </div>
          </div>
          
          {/* Material Selection */}
          <div className="mb-6">
            <h3 className="text-lg font-medium mb-3">材质</h3>
            <div className="grid grid-cols-2 gap-2">
              {["布料", "皮革", "绒布", "亚麻"].map((material) => (
                <button
                  key={material}
                  className={`py-2 px-4 rounded border ${
                    customization.material === material
                      ? "border-blue-500 bg-blue-50 text-blue-600"
                      : "border-gray-300 hover:border-gray-400"
                  }`}
                  onClick={() => handleMaterialChange(material)}
                >
                  {material}
                </button>
              ))}
            </div>
          </div>
          
          {/* Size Selection */}
          <div className="mb-6">
            <h3 className="text-lg font-medium mb-3">尺寸</h3>
            <div className="grid grid-cols-3 gap-2">
              {["小号", "中号", "大号"].map((size) => (
                <button
                  key={size}
                  className={`py-2 px-4 rounded border ${
                    customization.size === size
                      ? "border-blue-500 bg-blue-50 text-blue-600"
                      : "border-gray-300 hover:border-gray-400"
                  }`}
                  onClick={() => handleSizeChange(size)}
                >
                  {size}
                </button>
              ))}
            </div>
          </div>
          
          {/* Price and Action */}
          <div className="border-t pt-6">
            <div className="flex justify-between items-center mb-4">
              <span className="text-lg">总价:</span>
              <span className="text-2xl font-bold text-blue-600">¥{totalPrice}</span>
            </div>
            <button 
              className="w-full bg-blue-500 text-white font-semibold py-3 px-6 rounded-lg hover:bg-blue-600 transition duration-300"
              onClick={() => {
                addItem({
                  productId: parseInt(product.id || '1'),
                  name: product.name,
                  price: totalPrice,
                  quantity: 1,
                  color: customization.color,
                  material: customization.material,
                  size: customization.size
                });
                alert('商品已添加到购物车');
              }}
            >
              加入购物车
            </button>
          </div>
        </div>
      </div>
      
      {/* Product Description */}
      <div className="mt-8 bg-white rounded-lg shadow-md p-6">
        <h2 className="text-2xl font-semibold mb-4">产品描述</h2>
        <p className="text-gray-700">
          {product.description}。您可以根据个人喜好选择颜色、材质和尺寸，打造专属于您的家具。
        </p>
      </div>
    </div>
  );
};

export default Customization;